//
//  WHYStatusListViewModel.swift
//  WHYWeibo-1.0
//
//  Created by 王洪运 on 15/11/25.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit
import SDWebImage


class WHYStatusListViewModel {

    lazy var statusList = [WHYStatusViewModel]()
    
    var pullDownCount: Int?

    
}

// MARK: - 扩展函数
extension WHYStatusListViewModel {
    
    func loadStatus(isPullup isPullup: Bool, finished: (isSuccessed: Bool) -> ()) {
        
        let since_id = isPullup ? 0 : (statusList.first?.status.id ?? 0)
        let max_id = isPullup ? (statusList.last?.status.id ?? 0) : 0
        
            
        WHYStatusDAL.loadStatus(since_id, max_id: max_id) { (array) -> () in
                
            guard let array = array else {
                
                finished(isSuccessed: false)
                
                return
            }
            
            var dataList = [WHYStatusViewModel]()
            
            for dict in array {
                let status = WHYStatus(dict: dict)
                dataList.append(WHYStatusViewModel(status: status))
            }
            
//            拼接数组有先后的顺序
            if max_id > 0 {
                self.statusList += dataList//把获得数据加到后面，既上拉加载数据
            }else {
                self.statusList = dataList + self.statusList//把获得数据加到前面，既下拉刷新数据
            }
            
            self.pullDownCount = since_id > 0 ? dataList.count : nil
            
            self.cacheSingleImage(dataList, finished: finished)
            
        }
        
    }
    
    private func cacheSingleImage(array: [WHYStatusViewModel], finished: (isSuccessed: Bool) -> ()) {
        
        let group = dispatch_group_create()
        var dataLenth = 0
        
        for vm in array {
            if vm.thumbnailUrls?.count != 1 {
                continue
            }
            
            let url = vm.thumbnailUrls!.first
            
            SDWebImageManager.sharedManager().downloadImageWithURL(
                url,
                options: [SDWebImageOptions.RefreshCached, SDWebImageOptions.RetryFailed],
                progress: nil,
                completed: { (image, error, _, _, _) -> Void in
//SDWebImageOptions.RetryFailed:这个枚举会在下载失败后重新下载，也就是说会多发送一次调度组的leave，此时会崩溃。为了防止崩溃，需要将调度组的enter也放到回调中，这样，每次加载时调度组都会有对应的enter和leave函数
                    dispatch_group_enter(group)
                    
                    if let img = image,
                        data = UIImagePNGRepresentation(img) {
                            dataLenth += data.length
                    }
                    
//                    if let g = group {
//                        dispatch_group_leave(g)
//                    }
                    
                    dispatch_group_leave(group)
            })
            
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
//            QL2("缓存图片大小\(dataLenth / 1024) K")
            
            finished(isSuccessed: true)
        })
        
    }
    
}




